import wizard
import pooler
import datetime
from tools.translate import _
from osv import osv, fields

job_list_forms = '''
<form string="Job List">
    <group colspan="4" col="9">
        <field name="job_type" required="True" colspan="2" on_change="_onchange_type(job_type,from_job,to_job)"/>
        <newline/>
        <newline/>
        <newline/>
        <separator string='Job Selection' colspan="9"/>
        <field string="From" name="from_job" domain="[('project_type','in',[job_type])]" colspan="4"/>
        <field name="to_job" string="To" domain="[('project_type','in',[job_type])]" colspan="4"/>
    </group>
</form>'''

job_list_fields = {
        'job_type': {'string':'Job Type', 'type':'selection', 'selection':[('E','Electrical'),('M','Mechanical')],'required':True},
        'from_job': {'string':'From', 'type':'many2one','relation':'kdvn.project','required':True},
        'to_job': {'string':'To','type':'many2one','relation':'kdvn.project'}
    }

class class_for_onchange(osv.osv_memory): #Using onchange only
    _name='wizard.jreports.kdvn_report_job_list_from_to'
    _auto=False
    
    def _onchange_type(self, cr, uid, ids,job_type, from_job=False,to_job=False):
        pool = pooler.get_pool(cr.dbname)
        if from_job:
            prj_obj = pool.get('kdvn.project').read(cr,uid,from_job,['project_type'])
        else:
            prj_obj = False
        prj_type = False
        if prj_obj:
            prj_type = prj_obj['project_type']
        if job_type!=prj_type:
            from_job = False
            
        if to_job:
            prj_obj = pool.get('kdvn.project').read(cr,uid,to_job,['project_type'])
        else:
            prj_obj = False
             
        prj_type = False
        if prj_obj:
            prj_type = prj_obj['project_type']
        if job_type!=prj_type:
            to_job = False
            
        return {'value':{'from_job':from_job,'to_job':to_job}}
  
class_for_onchange()

class wizard_kdvn_report_job_list_from_to(wizard.interface):
   
    def _get_defaults(self, cr, uid, data, context={}):
        prj_id = False
        
        try:
            prj_id = data['ids']
        except:
            prj_id = data['id']
            
        pool = pooler.get_pool(cr.dbname)
        prj_obj = pool.get('kdvn.project').read(cr,uid,prj_id[0],['project_type'])
        
        if prj_obj:
            job_type = prj_obj['project_type']
            
        data['form']['job_type'] = job_type
        
        from_job = False
        to_job = False
        
        if prj_id:
            from_job = prj_id[0]
            prj_ids = ','.join(map(str,prj_id))
            cr.execute("Select id from kdvn_project where code =(Select min(code) from kdvn_project where id in (%s) and project_type='%s')" % (prj_ids,job_type))    
            
            from_job_obj = cr.fetchone()
            if from_job_obj:
                from_job = from_job_obj[0]

            cr.execute("Select id from kdvn_project where code =(Select max(code) from kdvn_project where id in (%s) and project_type='%s')" % (prj_ids,job_type))
            to_job_obj = cr.fetchone()
        
            if to_job_obj:
                to_job = to_job_obj[0]
             
        data['form']['from_job'] = from_job
        data['form']['to_job'] = to_job
        
        return data['form']

    def _get_records(self, cr, uid, data, context={}):
        #cr.execute('alter SEQUENCE new_id_job_list_from_to RESTART;')
        pool = pooler.get_pool(cr.dbname)
        ids=[]
        check=False
        from_id = data['form']['from_job']
        to_id = data['form']['to_job']
        
        if not to_id:
            where = "where code=(select code from kdvn_project where id=%s)" % from_id
        else:
            where = "where (code between (select code from kdvn_project where id=%s) and (select code from kdvn_project where id=%s)) \
                            or (code between (select code from kdvn_project where id=%s) and (select code from kdvn_project where id=%s))" % (from_id,to_id,to_id,from_id)

        cr.execute("Select id from kdvn_job_list_from_to_report where project_id in (Select id from kdvn_project " +where +")")
        #raise osv.except_osv("E","Select id::integer from kdvn_job_list_from_to_report where project_id in (Select id from kdvn_project " +where +")")
        report_ids_tmp = cr.fetchall()
        report_ids = []
        for rp_id in report_ids_tmp:
            if type(rp_id).__name__=='tuple':
                report_ids.append(rp_id[0])
            else:
                 report_ids.append(rp_id)
        from_job =''
        if from_id:
            from_job_obj = pool.get('kdvn.project').read(cr,uid,from_id,['code'])
            if from_job_obj:
                from_job = from_job_obj['code']

        to_job =''
        if to_id:
            from_job_obj = pool.get('kdvn.project').read(cr,uid,to_id,['code'])
            if from_job_obj:
                to_job = from_job_obj['code']

        data['ids']=report_ids
        data['model']='kdvn.job.list.from.to.report'
        
        if report_ids:
            data['form']['id'] = report_ids[0] 
            data['form']['ids'] = report_ids
            data['id'] = report_ids[0]
        
        return {'ids' :report_ids,'from_job':from_job,'to_job':to_job,'id':data['id'],'model':'kdvn.job.list.from.to.report', 'title' : 'Job List Report'} 
        
    states = {
         'init': {
            'actions': [_get_defaults],
            'result': {
                'type': 'form',
                'arch':job_list_forms,
                'fields':job_list_fields,
                'state':[('end','Cancel','gtk-cancel'),('print_report','Print','gtk-print')]
            },
        },
        'print_report': {
            'actions': [_get_records],
            'result': {
                'type': 'print',
                'name' : 'Job List',
                'report': 'Job.List',
                'state': 'end'
            },
        }, 
    }
wizard_kdvn_report_job_list_from_to('jreports.kdvn_report_job_list_from_to')